package javase.javase02.networkprograming;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Properties;

/**
 * @author: Gan
 * @date 2021/4/23 0023 16:43
 * @description:
 **/
public class Receiver {
    public static void main(String[] args) throws IOException {
        // 创建用于接收的socket对象
        DatagramSocket datagramSocket = new DatagramSocket(54321);
        // 创建properties对象
        Properties properties = new Properties();
        //
        properties.load(new InputStreamReader(
                new FileInputStream("dataDict.properties"),"GBk"));
        while (true) {
            // 接收数据
            DatagramPacket receiverPacket = NetworkUtils.getReceiverPacket();
            datagramSocket.receive(receiverPacket);
            String key = NetworkUtils.parsePacket(receiverPacket);
            String responseMsg = properties.getProperty(key);
            System.out.println(responseMsg);
            if (responseMsg == null) {
                // 如果没有匹配上  返回一个默认的字符串
                responseMsg = "正在忙,稍后回复";
            }
            // 返回给发送端
            DatagramPacket senderPacket =
                    NetworkUtils.getSenderPacket("127.0.0.1", 12345, responseMsg);
            datagramSocket.send(senderPacket);
            if (key.equals("86")) {
                break;
            }
        }
        datagramSocket.close();
    }
}
